//
//  MyBusinessCardWXData.m
//  ZhuiKe55like
//
//  Created by junseek on 16/7/1.
//  Copyright © 2016年 五五来客 李江. All rights reserved.
//

#import "MyBusinessCardWXData.h"
#import "AlertZKView.h"
#import "XHImageUrlViewer.h"
#import <ZYQAssetPickerController.h>

@interface MyBusinessCardWXData ()<UITextFieldDelegate,XHImageUrlViewerDelegate,AlertZKViewDelegate,ZYQAssetPickerControllerDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate>{
    UITextField *txtContent;
    UIImageView *imageViewTemp;
    UIButton *btnAddImage;
    XHImageUrlViewer *imageViewer;
    
    AlertZKView *alertZk;
    UIImagePickerController *ipc;
    
    UIImage *imageTemp;
    
}

@end

@implementation MyBusinessCardWXData

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    [self rightButton:@"确定" image:@"" sel:@selector(rightButtonClicked)];
        
    
    
    UIView *viewBG=[[UIView alloc] initWithFrame:CGRectMake(-1,kTopHeight +20, kScreenWidth+2, 44)];
    viewBG.backgroundColor=[UIColor whiteColor];
    [self.view addSubview:viewBG];
    viewBG.backgroundColor=[UIColor whiteColor];
    viewBG.layer.borderWidth=0.5;
    viewBG.layer.borderColor =[rgbLineColor CGColor];


    txtContent=[RHMethods textFieldlWithFrame:CGRectMake(10, Y(viewBG), kScreenWidth-20, H(viewBG)) font:fontTitle color:rgbTitleColor placeholder:@"请输入" text:[self.otherInfo valueForJSONStrKey:@"wechat"]];
    txtContent.delegate=self;
    [self.view addSubview:txtContent];
//    [txtContent becomeFirstResponder];
    
    float fw=63;
    float fx=10;
    [self.view addSubview:[RHMethods labelWithFrame:CGRectMake(10, YH(viewBG)+20, 0, 20) font:fontSmallTitle color:rgbTxtGray text:@"上传微信二维码"]];
    imageViewTemp=[RHMethods imageviewWithFrame:CGRectMake(fx, YH(viewBG)+45, fw, fw) defaultimage:@""];
    [self.view addSubview:imageViewTemp];
    imageViewTemp.userInteractionEnabled=YES;
    UITapGestureRecognizer *tapImage=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(logoImageClicked:)];
    [imageViewTemp addGestureRecognizer:tapImage];
    
    
    imageTemp=[self.otherInfo objectForKey:@"imageData"];
    if (imageTemp) {
        imageViewTemp.image=imageTemp;
        fx+=fw+10;
    }else if ([[self.otherInfo valueForJSONStrKey:@"wxicon"] notEmptyOrNull]) {
        [imageViewTemp imageWithURL:[self.otherInfo valueForJSONStrKey:@"wxicon"] useProgress:NO useActivity:NO];
        fx+=fw+10;
    }else{
        imageViewTemp.hidden=YES;
    }
    
    btnAddImage=[RHMethods buttonWithFrame:CGRectMake(fx, Y(imageViewTemp), fw, fw) title:@"" image:@"addIcon070116" bgimage:@""];
    btnAddImage.imageView.contentMode = UIViewContentModeScaleAspectFill;
    [btnAddImage addTarget:self action:@selector(imageAddButtonClicked) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btnAddImage];
    
    
    
}

-(void)loadRefrshImageViewData{
    if (imageTemp) {
        imageViewTemp.hidden=NO;
        btnAddImage.frameX=XW(imageViewTemp)+10;
        imageViewTemp.image=imageTemp;
    }else{
        imageViewTemp.hidden=YES;
        btnAddImage.frameX=X(imageViewTemp);
    }
    
}
-(void)logoImageClicked:(UITapGestureRecognizer *)tap{
    
    [self.view endEditing:YES];
    //放大图片
    if (!imageViewer) {
        imageViewer = [[XHImageUrlViewer alloc] init];
    }
    imageViewer.delegate=self;
    imageViewer.hiddenDeleteButton=NO;
    
    NSInteger selectIndex = 0;
    NSMutableArray *array=[[NSMutableArray alloc] init];
   
    NSMutableDictionary *dt=[[NSMutableDictionary alloc] init];
    if (imageTemp) {
        [dt setValue:imageTemp forKey:@"DefaultImage"];
    }else if ([self.otherInfo valueForJSONStrKey:@"wxicon"]){
        [dt setValue:[self.otherInfo valueForJSONStrKey:@"wxicon"] forKey:@"url"];
    }
    
    [array addObject:dt];
    
    [imageViewer showWithImageDatas:array selectedIndex:selectIndex];
    

}
#pragma mark XHImageViewerDelegate
//删除操作后剩下的imageArray
- (void)imageUrlViewer:(XHImageUrlViewer *)view deleteArray:(NSArray*)deleteArray remainArray:(NSArray *)remainArray{
    DLog(@"deleteArray:%@____________remainArray:_%@",deleteArray,remainArray);

    if ([deleteArray count]) {
        imageTemp=nil;
        [self loadRefrshImageViewData];
    }
    
}

#pragma mark button
-(void)rightButtonClicked{
    
    [self backButtonClicked:nil];
//    NSMutableDictionary *dicT=[NSMutableDictionary new];
//    [dicT setValue:[[Utility Share] userToken] forKey:@"token"];
//    [dicT setValue:[[Utility Share] userId] forKey:@"uid"];
//    [dicT setValue:txtContent.text forKey:@"wechat"];
//    
//    NSMutableArray *arrayT=[NSMutableArray new];
//    if (imageTemp) {
//        NSData *data = [NSData dataWithData:UIImageJPEGRepresentation(imageTemp, 1.0)];
//        [arrayT addObject:[NSDictionary dictionaryWithObjectsAndKeys:data,@"fileData",@"wxicon",@"fileKey",@"xxxx.jpg",@"fileName", nil]];
//    }
//    
//    [NetEngine uploadAllFileAction:XKFuserprofiles withParams:dicT fileArray:arrayT onCompletion:^(id resData, BOOL isCache) {
//        if ([[resData valueForJSONStrKey:@"status"] isEqualToString:@"200"]) {
//            [SVProgressHUD showSuccessWithStatus:[resData valueForJSONStrKey:@"info"]];
//            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.8 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                [super backButtonClicked:nil];
//            });
//        }else{
//            [SVProgressHUD showImage:nil status:[resData valueForJSONStrKey:@"info"]];
//        }
//    } onError:^(NSError *error) {
//        [SVProgressHUD showImage:nil status:alertErrorTxt];
//    } withMask:SVProgressHUDMaskTypeClear];
//    

    
}
-(void)imageAddButtonClicked{
    [self.view endEditing:YES];
    
        if (!alertZk) {
            alertZk =[[AlertZKView alloc]init];
        }
        alertZk.delegate=self;
        alertZk.userArray=[[NSArray alloc] initWithObjects:@"从相册选取",@"拍照", nil];
        alertZk.strTitle=@"添加图片";
        [alertZk show];
    

}

#pragma mark AlertZKViewDelegate
-(void)AlertSelectZKView:(AlertZKView *)sview clickedButtonAtIndex:(NSInteger)aIndex{
    if (!ipc) {
        ipc=[[UIImagePickerController alloc]init];
    }
    
    if (aIndex==0) {
        
        
        ZYQAssetPickerController *ZYQPicker = [[ZYQAssetPickerController alloc] init];
        ZYQPicker.maximumNumberOfSelection = 1;
        ZYQPicker.minimumNumberOfSelection=1;
//        ZYQPicker.assetsFilter = [ALAssetsFilter allPhotos];
        ZYQPicker.showEmptyGroups=NO;
        ZYQPicker.delegate=self;
        ZYQPicker.showEditImageView=YES;
        
       
        SendNotify(ZKHiddenAudioPlayBtton, nil)
        
        [self presentViewController:ZYQPicker animated:YES completion:^{
            if (kVersion7) {
                [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
            }
        }];
    }else if (aIndex==1){
        if (kVersion7) {
            NSString *mediaType = AVMediaTypeVideo;
            AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
            if(authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied){
                NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
                NSString *app_Name = [infoDictionary objectForKey:@"CFBundleDisplayName"];
                [[Utility Share] showAccessPermissionsAlertViewMessage:[NSString stringWithFormat:@"‘%@’没有访问相机的权限，请前往【设置】允许‘%@’访问",app_Name,app_Name]];
                
                return;
            }
        }
        //判断当前相机是否可用
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
        {// 打开相机
            ipc.sourceType = UIImagePickerControllerSourceTypeCamera;
            //设置是否可编辑
            ipc.allowsEditing = NO;
            ipc.delegate=self;
            SendNotify(ZKHiddenAudioPlayBtton, nil)
            //打开
            [self presentViewController:ipc animated:YES completion:^{
                
            }];
        }else
        {
            //如果不可用
            UIAlertView *alert=[[UIAlertView alloc]initWithTitle:nil message:@"设备不可用..." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil ];
            [alert show];
        }
        
    }
}




#pragma mark - ZYQAssetPickerController Delegate
-(void)assetPickerController:(ZYQAssetPickerController *)picker didFinishPickingAssets:(NSArray *)assets{
    
}
-(void)assetPickerControllerDidMaximum:(ZYQAssetPickerController *)picker{
    [SVProgressHUD showImage:nil status:[NSString stringWithFormat:@"您只能选择%ld张",(long)picker.maximumNumberOfSelection]];
}
-(void)assetPickerController:(ZYQAssetPickerController *)picker cropImage:(UIImage *)cropImage forOriginalImage:(UIImage *)originalImage{
    //处理图片
    imageTemp=[[Utility Share] imageWithImageSimple:cropImage scaledToSize:CGSizeMake(kScreenWidth*2, kScreenWidth*2)];
    [self loadRefrshImageViewData];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
}
#pragma mark UIImagePickerControllerDelegate
//设备协议
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    DLog(@"_____info:%@",info);
    //获得编辑过的图片
    UIImage *image=[info objectForKey:UIImagePickerControllerOriginalImage];
    
    CGSize size =  image.size ;
    CGFloat fullW = kScreenWidth*2;
    CGFloat fullH = kScreenWidth*2;
    CGFloat ratio = MIN(fullW / size.width, fullH / size.height);
    ratio = ratio>1?1:ratio;
    CGFloat W = ratio * size.width;
    CGFloat H = ratio * size.height;
    
    imageTemp=[[Utility Share] imageWithImageSimple:image scaledToSize:CGSizeMake(W, H)];
    [self loadRefrshImageViewData];
    
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
    
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
    
}


-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self refreshPopData];
}

-(void)refreshPopData{
//   if ([self.userInfo isEqualToString:@"updateBusinessCard"]){
        //
       NSMutableDictionary *dci=[[NSMutableDictionary alloc] init];
       [dci setValue:txtContent.text forKey:@"wechat"];
       [dci setValue:@"微信号" forKey:@"title"];
       if (imageTemp) {
           [dci setObject:imageTemp forKey:@"imageData"];
       }else if(!imageViewTemp.hidden && [[self.otherInfo valueForJSONStrKey:@"wxicon"] notEmptyOrNull]){
           [dci setValue:[self.otherInfo valueForJSONStrKey:@"wxicon"] forKey:@"wxicon"];
       }
       
       
       
        for (id controller in self.navigationController.viewControllers) {
            if ([NSStringFromClass([controller class]) isEqualToString:@"UpdateUserDataViewController"]) {
                if ([(NSObject*)controller respondsToSelector:@selector(popRefreshDataWX:)]) {
                    
                    [controller performSelector:@selector(popRefreshDataWX:) withObject:dci afterDelay:0.01];
                }
                break;
            }
            
        }
//    }
}

#pragma mark UITextFieldDelegate
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
   
    [self backButtonClicked:nil];
    
    
    
    return YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
